import sys

# 直接复用Pipeline实例
sys.path.append("./")
pipeline = __import__("04-question-answering")

import gradio as gr


# 定义问答函数
def answer_question(question, context):
    result = pipeline.nlp(question=question, context=context)
    return f"答案: {result['answer']}, 置信度: {result['score']:.4f}"


# 创建Gradio界面
with gr.Blocks() as demo:
    gr.Markdown("# 问答系统")
    gr.Markdown(
        "这是一个基于Transformers框架的问答工具。您可以输入一个问题和一段文本，点击“提交”按钮后，系统将尝试从中找到答案。")

    with gr.Row():
        input_context = gr.Textbox(placeholder="请输入相关文本...", label="上下文")

    with gr.Row():
        input_question = gr.Textbox(placeholder="请输入您的问题...", label="问题")

    with gr.Row():
        submit_button = gr.Button("提交")

    with gr.Row():
        output_answer = gr.Label(label="答案")

    # 设置按钮点击事件，触发问答函数
    submit_button.click(answer_question, inputs=[input_question, input_context], outputs=output_answer)

# 启动Gradio应用
if __name__ == "__main__":
    demo.launch()
